﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;

public partial class Customer_Customer : System.Web.UI.Page
{
    private enum Views
    {
        MainView = 0,
        AddProductView = 1
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ApplyAuthorizationRules();
        }
    }

    private void ApplyAuthorizationRules()
    {
        Customer obj = GetCustomer();
        // Customer display
        if (Customer.CanEditObject())
        {
            if (obj.IsNew)
            {
                this.CustomerDetailsView.DefaultMode = DetailsViewMode.Insert;
                this.ProductListPlaceHolder.Visible = false;
            }
            else
            {
                this.CustomerDetailsView.DefaultMode = DetailsViewMode.Edit;
            }
        }
        else
        {
            this.CustomerDetailsView.DefaultMode = DetailsViewMode.ReadOnly;
        }

        this.ProductsGridView.Columns[ProductsGridView.Columns.Count - 1].Visible = 
            Customer.CanEditObject();
        this.btnAddProduct.Visible = Customer.CanAddObject();
    }

    #region BusinessObject

    private Customer GetCustomer()
    {
        string idString = Request.QueryString["id"];
        object businessObj = Session["CurrentObj"];
        if (businessObj == null
            || !(businessObj is Customer)
            || (!IsPostBack && !((Customer)businessObj).Id.ToString().Equals(idString)))
        {
            try
            {
                if (!string.IsNullOrEmpty(idString))
                {
                    businessObj = Customer.GetCustomer(int.Parse(idString));
                }
                else
                {
                    businessObj = Customer.NewCustomer();
                }
                Session["CurrentObj"] = businessObj;
            }
            catch (System.Security.SecurityException)
            {
                Response.Redirect("~/Customer");
            }
        }
        return businessObj as Customer;
    }

    private int SaveCustomer(Customer customer)
    {
        int rowsAffected = 0;
        try
        {
            Session["CurrentObj"] = customer.Save();
            rowsAffected = 1;
        }
        catch (Csla.Validation.ValidationException ex)
        {
            throw;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
        return rowsAffected;
    }

    #endregion

    #region CustomerDataSource

    protected void CustomerDataSource_DeleteObject(object sender, Csla.Web.DeleteObjectArgs e)
    {
        try
        {
            Customer.DeleteCustomer(int.Parse(e.Keys["Id"].ToString()));
            Session["currentObj"] = null;
            e.RowsAffected = 1;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    protected void CustomerDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        Customer obj = GetCustomer();
        Csla.Data.DataMapper.Map(e.Values, obj);
        e.RowsAffected = SaveCustomer(obj);
    }

    protected void CustomerDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetCustomer();
    }

    protected void CustomerDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Customer obj = GetCustomer();
        Csla.Data.DataMapper.Map(e.Values, obj);
        e.RowsAffected = SaveCustomer(obj);
    }

    #endregion

    #region CustomerDetailsView

    protected void CustomerDetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        Customer obj = GetCustomer();
        if (!obj.IsNew)
        {
            Response.Redirect("~/Customer/Customer.aspx?id=" + obj.Id.ToString(), true);
        }
    }

    protected void CustomerDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        Label error = CustomerDetailsView.FindControl("lblNameError") as Label;
        if (Customer.CheckNameIsUsed(e.Values["Name"].ToString()))
        {
            error.Text = "客户名称已存在，请重新输入。";
            e.Cancel = true;
        }
        else
        {
            error.Text = "";
        }
    }

    protected void CustomerDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        Label error = CustomerDetailsView.FindControl("lblNameError") as Label;
        if (e.OldValues["Name"].ToString() != e.NewValues["Name"].ToString()
            && Customer.CheckNameIsUsed(e.NewValues["Name"].ToString()))
        {
            error.Text = "客户名称已存在，请重新输入。";
            e.Cancel = true;
        }
        else
        {
            error.Text = "";
        }
    }

    #endregion

    protected void btnAddProduct_Click(object sender, EventArgs e)
    {
        this.MultiView1.ActiveViewIndex = (int)Views.AddProductView;
    }

    protected void btnCancelSaveProduct_Click(object sender, EventArgs e)
    {
        this.MultiView1.ActiveViewIndex = (int)Views.MainView;
    }

    #region ProductDataSource

    protected void ProductDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        Customer cust = GetCustomer();
        Product product = cust.Products.AddNew();
        Csla.Data.DataMapper.Map(e.Values, product);
        SaveCustomer(cust);

        Response.Redirect("~/Customer/Customer.aspx?id=" + cust.Id.ToString(), true);
    }

    #endregion

    #region ProductsDataSource

    protected void ProductsDataSource_DeleteObject(object sender, Csla.Web.DeleteObjectArgs e)
    {
        Customer cust = GetCustomer();
        cust.Products.Remove(int.Parse(e.Keys["Id"].ToString()));
        SaveCustomer(cust);
        e.RowsAffected = 1;
    }

    protected void ProductsDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetCustomer().Products;
    }

    protected void ProductsDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Customer cust = GetCustomer();
        Product product = cust.Products.GetProductById(int.Parse(e.Keys["Id"].ToString()));
        product.Name = e.Values["Name"] as string;
        product.Versions = 
            e.Values["Versions"] != null ? e.Values["Versions"].ToString() : string.Empty;
        SaveCustomer(cust);

        e.RowsAffected = 1;
    }

    #endregion
}
